
package com.lzx.adx.report.controller.v1.sfkj;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.sfkj.SfkjRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 媒体：优优
 * 产品夸克
 */
@RequestMapping("/sfkj/yeyu")
@RestController
@Slf4j
public class SfkjYeYuReportController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;


    @GetMapping("/report")
    public ResponseEntity report(SfkjRequest sfkjRequest) {
        log.info("接收到山风科技到夜雨的请求参数为{}", JsonUtils.toJsonString(sfkjRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = sfkjRequest.builderReportDTO();
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(sfkjRequest.getDspId());
        String finalUrl = KkHeper.covertYeYu(accountDTO, reportDTO);
        log.info("账号为{}完整的山风科技到夜雨请求地址为{}", sfkjRequest.getDspId(), finalUrl);
        //2.2夸克上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{}完整的山风科技到夜雨响应的结果为{}", sfkjRequest.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }

    /**
     * 夸克回传
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/tt/callback")
    public ResponseEntity ttCallBackUrl(String requestId, String action_type) throws Exception {
        log.info("山风科技夜雨-头条回调信息,请求流水号{} 请求类型{}", requestId,action_type);
        if (StringUtils.isBlank(requestId)||StringUtils.isBlank(action_type)) {
            log.info("山风科技-夜雨-头条回调信息参数异常不做处理");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        if (!"activate".equals(action_type)){
            log.info("山风科技-夜雨-头条回调信息,请求流水号{} 请求类型{} 不是激活,不处理", requestId,action_type);
            return ResponseEntity.ok(new Result());
        }
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        String time = String.valueOf(System.currentTimeMillis());
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType("1");
            reportDTO.setResultTime(time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,action_type);
        } else {
            log.error("回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("transformType", "1");
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("dspId{},请求流水号{}夜雨-头条回调山风科技的完整地址为：{}", reportDTO.getDspId(), requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("dspId{},请求流水号{}夜雨-头条回调山风科技的结果为：{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }





    /**
     * 夸克回传
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/bz/callback")
    public ResponseEntity bzCallBackUrl(String requestId, String action_type) throws Exception {
        log.info("山风科技夜雨-哔哩哔哩回调信息,请求流水号{} 请求类型{}", requestId,action_type);
        if (StringUtils.isBlank(requestId)||StringUtils.isBlank(action_type)) {
            log.info("山风科技-夜雨-头条回调信息参数异常不做处理");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        if (!"activate".equals(action_type)){
            log.info("山风科技-夜雨-哔哩哔哩回调信息,请求流水号{} 请求类型{} 不是激活,不处理", requestId,action_type);
            return ResponseEntity.ok(new Result());
        }
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        String time = String.valueOf(System.currentTimeMillis());
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(action_type);
            reportDTO.setResultTime(time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,action_type);
        } else {
            log.error("回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("transformType", "1");
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("dspId{},请求流水号{}夜雨-哔哩哔哩回调山风科技的完整地址为：{}", reportDTO.getDspId(), requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("dspId{},请求流水号{}夜雨-哔哩哔哩回调山风科技的结果为：{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


}
